import {Injectable} from '@angular/core';
import {Overlay, OverlayConfig, OverlayRef} from '@angular/cdk/overlay';
import {ComponentPortal} from '@angular/cdk/portal';
import {MessageComponent} from './message.component';

interface MessageConfig {
  panelClass?: string;
  hasBackDrop?: boolean;
  backDropClass?: string;
}

const DEFAULT_CONFIG: MessageConfig = {
  panelClass: 'tm-file-preview-dialog-panel',
  hasBackDrop: true,
  backDropClass: 'dark-backdrop'
};

@Injectable({
  providedIn: 'root'
})
export class MessageService {

  overlayRef: OverlayRef;

  constructor(
    private overlay: Overlay
  ) {
  }

  open(config: MessageConfig = {}): OverlayRef {

    // overlay配置
    const messageConfig = {...DEFAULT_CONFIG, ...config};
    // 创建ref
    this.overlayRef = this.createOverlay(messageConfig);

    const messagePortal = new ComponentPortal(MessageComponent);

    this.overlayRef.attach(messagePortal);

    this.overlayRef.backdropClick().subscribe(_ => this.close());

    return this.overlayRef;
  }

  // 创建overlay
  private createOverlay(config: MessageConfig): OverlayRef {

    const messageConfig = this.getOverlayConfig(config);

    return this.overlay.create(messageConfig);
  }

  /**
   * 配置
   * @param config 用户传的配置信息
   */
  private getOverlayConfig(config: MessageConfig): OverlayConfig {

    // 位置定位策略
    const positionStrategy = this.overlay.position()
      .global()
      .centerHorizontally()
      .centerVertically();

    // 配置
    return new OverlayConfig({
      hasBackdrop: config.hasBackDrop,
      backdropClass: config.backDropClass,
      panelClass: config.panelClass,
      scrollStrategy: this.overlay.scrollStrategies.block(),
      positionStrategy
    });
  }

  // 关闭弹框
  close(): void {
    this.overlayRef.dispose();
  }
}
